import Cookies from 'js-cookie'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import fileUtil from '@/utils/fileUtil'

const TokenKey = 'X-Litemall-Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function checkUploadUrl(response) {
  // console.log('checkUploadUrl',response)
  if (response.errno === 501) {
    MessageBox.alert('系统未登录，请重新登录', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    }).then(() => {
      store.dispatch('FedLogOut').then(() => {
        location.reload()
      })
    })
  }else if(response.errno !==0){
    Message({
      type: 'error',
      message: response.msg
    })
    return
  }
}
export function beforeUploadFn(file) {
  //处理上传图片旋转问题
    //校验图片最大上传10M
  var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)  
  const isLt2M = file.size / 1024 / 1024 < 10
  if(!isLt2M) {  
    Message({  
        message: '上传文件大小不能超过 10MB!',  
        type: 'warning'  
    }); 
    return isLt2M;
  }else{
    return new Promise((resolve) => {
      fileUtil.getOrientation(file).then((orient) => {
        console.log('orient',orient)
        // if (orient && orient === 6) {
        if (orient) {
          let reader = new FileReader()
          reader.readAsDataURL(file)
          let img = new Image()
          reader.onload = (e) => {
            img.src = e.target.result
            img.onload = function () {
                const data = fileUtil.rotateImage(img, img.width, img.height)
                const newFile = fileUtil.dataURLtoFile(data, file.name)
                console.log('orient-newFile',newFile)
                resolve(newFile)
            }
          }
          // reader.readAsDataURL(file)
        } else {
          resolve(file)
        }
      })
    })
  }
}
